<template>
  <div class="page">
    <el-dialog
      v-el-drag-dialog
      title="新增用户"
      :visible.sync="visible"
      width="824px"
      @closed="reset"
    >
      <el-form ref="dataForm" class="form1" :model="queryForm" label-position="left">
        <el-form-item label="用户编号:" label-width="80px">
          <el-input v-model.trim="queryForm.csmCode" style="width: 250px;" placeholder="请输入">
            <el-button slot="append" type="primary" icon="el-icon-search" :loading="$loadingPlugin.searchForPhone" @click="searchForCode">查询</el-button>
          </el-input>
        </el-form-item>
      </el-form>
      <el-descriptions title="用户信息" size="medium" :column="3" :label-style="labelStyle" :content-style="contentStyle">
        <el-descriptions-item label="用户编号">{{ csmInfo.csmCode }}</el-descriptions-item>
        <el-descriptions-item label="用户姓名">{{ csmInfo.csmName }}</el-descriptions-item>
        <el-descriptions-item label="用户性质">{{ formatColumnMap(customerTypeMap, Number(csmInfo.csmType)) }}</el-descriptions-item>
        <el-descriptions-item label="用户机构">{{ csmInfo.orgName }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions v-for="(item,index) in csmInfo.addressItems" :key="index">
        <el-descriptions-item :label="'配送地址'+(index+1)">{{ item.csmAddress }}</el-descriptions-item>
        <el-descriptions-item label="门牌号">{{ item.doorplate }}</el-descriptions-item>
        <el-descriptions-item label="楼层">{{ item.csmFloor }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions v-if="csmInfo.bindStatus" :label-style="{'color':'red'}" :content-style="{'color':'red'}">
        <el-descriptions-item label="是否已绑定司机">{{ csmInfo.bindStatus?'是':'否' }}</el-descriptions-item>
        <el-descriptions-item label="司机所属机构">{{ csmInfo.driverOrgName }}</el-descriptions-item>
        <el-descriptions-item label="司机姓名">{{ csmInfo.driverName }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions v-else>
        <el-descriptions-item label="是否已绑定司机">{{ csmInfo.bindStatus?'是':'否' }}</el-descriptions-item>
      </el-descriptions>
      <div style=" font-size: 16px; font-weight: 700; color: #303133;">绑定司机</div>
      <el-form ref="dataForm" class="form" :model="dataForm" :rules="rules" label-position="left">
        <el-form-item label="新司机所属机构:" prop="orgSNNo">
          <el-tree-select
            v-model="dataForm.orgSNNo"
            class="tree-select"
            clearable
            :disabled="orgDisabled"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择',
              loading: $loadingPlugin.getTreeData,
            }"
            :tree-params="{
              'expand-on-click-node': false,
              'highlight-current': false,
              'filterable': true,
              props: {
                value: 'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData,
            }"
            @node-click="selectTreeChange"
            @select-clear="selectClearable"
          />
        </el-form-item>
        <el-form-item label="新司机:" prop="driverCode">
          <el-select v-model="dataForm.driverCode" filterable placeholder="请选择">
            <el-option
              v-for="item in driverList"
              :key="item.userCode"
              :label="item.userName"
              :value="item.userCode"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="$loadingPlugin.del" type="danger" @click="cancel('dataForm')">
          取消
        </el-button>
        <el-button :loading="$loadingPlugin.success" type="primary" @click="sumbit('dataForm')">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { csmDriverQueryCsm, csDeliverUserList, addBindcsmDriver } from '@/api'
  import { mapGetters } from 'vuex'
  import { formatColumnMap } from '@/utils'
  export default {
    components: {

    },
    props: {
      customerTypeMap: {
        type: Array,
        default: []
      },
      treeData: {
        type: Array,
        default: []
      },
      parentFetchData: {
        type: Function
      }
    },
    data() {
      return {
        visible: false,
        orgDisabled: false,
        driverList: [],
        queryForm: {
          csmCode: ''
        },
        csmInfo: {},
        dataForm: {
          orgSNNo: '',
          driverCode: '',
          driverName: ''
        },
        rules: {
          orgSNNo: [{ required: true, message: '请选择机构', trigger: 'change' }],
          driverCode: [{ required: true, message: '请选择司机', trigger: 'change' }]
        },
        labelStyle: { 'white-space': 'nowrap' },
        contentStyle: { 'word-break': 'break-all' }
      }
    },
    computed: {
      ...mapGetters(['orgList'])
    },
    watch: {

    },
    mounted() {

    },
    destroyed() {

    },
    methods: {
      formatColumnMap(map, value) {
        return formatColumnMap(map, 'value', value, 'desc')
      },
      open() {
        // return new Promise(resolve => {
        //   this.resolve = resolve
        this.visible = true
        // })
      },
      async searchForCode() {
        if (!this.queryForm.csmCode) {
          this.$message.error('请输入用户编号')
          return
        }
        const res = await csmDriverQueryCsm({ csmCode: this.queryForm.csmCode })
        if (!res.data) {
          this.$message.error('未查找到客户信息')
          return
        }
        this.csmInfo = res.data
        if (this.csmInfo.bindStatus) {
          this.dataForm.orgSNNo = res.data.driverOrgSNNo
          this.dataForm.orgId = res.data.driverOrgId
          this.dataForm.orgName = res.data.driverOrgName
          await this.selectTreeChange({ orgSNNo: this.csmInfo.driverOrgSNNo })
          // this.orgDisabled = true
        } else {
          this.dataForm.orgSNNo = res.data.orgSNNo
          this.dataForm.orgId = res.data.orgId
          this.dataForm.orgName = res.data.orgName
          await this.selectTreeChange(res.data)
          // this.orgDisabled = true
        }
      },
      // 选择所属机构
      async selectTreeChange(value) {
        console.log(value)
        this.driverList = []
        const res = await csDeliverUserList({ deliveryOrgId: value.orgId, utype: 8388640 })
        if (this.csmInfo.bindStatus) {
          this.driverList = res.data.filter(item => item.userCode !== this.csmInfo.driverCode)
        } else {
          this.driverList = res.data
        }
        this.dataForm.driverCode = null
      },
      selectClearable() {
        this.dataForm.driverCode = ''
        this.driverList = []
      },
      // 取消
      async cancel(formName) {
        await this.reset()
        this.visible = false
      },
      // 保存
      sumbit(formName) {
        if (!this.csmInfo.csmId) {
          this.$message.error('未查找客户')
          return
        }
        if (this.csmInfo.bindStatus) {
          this.$message.error('该用户已在其他站点绑定了大车司机 ')
          return
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const form = {
              driverCode: this.dataForm.driverCode,
              csmId: this.csmInfo.csmId
            }
            // console.log(form)
            this.$confirm(`一旦确认之后，该用户会绑定为该大车司机的用户，今后该用户配送就属于该司机配送, 是否继续?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              dangerouslyUseHTMLString: true,
              type: 'warning'
            }).then(() => {
              addBindcsmDriver(form).then(res => {
                this.$notify({
                  title: '提示',
                  message: '新增用户绑定成功',
                  type: 'success',
                  duration: 2000
                })
                this.parentFetchData({})
                this.visible = false
              }).catch(err => {
                console.log(err)
                this.visible = false
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              })
            })
          } else {
            return false
          }
        })
      },
      reset() {
        this.$refs.dataForm.resetFields()
        this.queryForm.csmCode = ''
        this.orgDisabled = false
        this.csmInfo = {}
        this.driverList = []
        this.dataForm = {
          orgSNNo: '',
          orgId: null,
          orgName: '',
          driverCode: null
        }
      }
    }
  }
</script>

<style lang='scss' scoped>
.form1 {
  display: flex;
  flex-wrap: wrap;
}
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    display: flex;
    width: 50%;
    padding-right: 10px;
    // .el-form-item__content {
    //   width: 100%;
    // }
  }
}
.el-form-item .el-form-item {
  margin-bottom: 0;
}
</style>
